package com.write.program.gui;

import com.write.program.db.dao.UserDao;
import com.write.program.db.meta.User;
import com.write.program.util.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2020-05-13
 * Time: 9:35
 */
public class LoginGui extends JFrame implements ActionListener {
	public static final int WIDTH = 500;
	public static final int HEIGHT = 400;

	private JPanel loginJPanel, userJPanel;
	private JTextField userNameField, passwordField;
	private JButton loginBtn;

	public static User loginUser;

	public static void main(String[] args) {
		new LoginGui();
	}

	public LoginGui() {
		this.setSize(WIDTH, HEIGHT);
		this.setLocationRelativeTo(null);//窗口居中显示 setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		loginJPanel = initLoginJPanel();
		this.add(loginJPanel, BorderLayout.CENTER);

		this.setVisible(true);
	}

	public JPanel initLoginJPanel() {
		JPanel loginJPanel = new JPanel();
		loginJPanel.setLayout(null);

		JLabel jLabel = new JLabel("Username:");
		jLabel.setBounds(100, 100, 70, 20);
		loginJPanel.add(jLabel);

		jLabel = new JLabel("Password:");
		jLabel.setBounds(100, 140, 70, 20);
		loginJPanel.add(jLabel);

		userNameField = new JTextField();
		userNameField.setBounds(170, 100, 160, 25);
		loginJPanel.add(userNameField);

		passwordField = new JTextField();
		passwordField.setBounds(170, 140, 160, 25);
		loginJPanel.add(passwordField);

		loginBtn = new JButton("Login");
		loginBtn.setBounds(200, 180, 80, 25);
		loginBtn.addActionListener(this);
		loginJPanel.add(loginBtn);

		loginJPanel.setVisible(true);
		return loginJPanel;
	}


	private void turnToUserJPanel() {
		if (userJPanel == null) {
			userJPanel = initUserJPanel();
		}
		loginJPanel.setVisible(false);

		this.add(userJPanel, BorderLayout.CENTER);
		userJPanel.setVisible(true);
	}

	private JPanel initUserJPanel() {
		return null;
	}



	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(loginBtn)) {
			String username = userNameField.getText();
			String password = passwordField.getText();
			if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
				JOptionPane.showMessageDialog(null, "Input username or password", "Notice", JOptionPane.WARNING_MESSAGE);
				return;
			}
			User user = UserDao.getInstance().getByUsername(username);
			if (user != null && user.getPassword().equals(password)) {
				loginUser = user;
				userNameField.setText("");
				passwordField.setText("");
				turnToUserJPanel();
			} else {
				JOptionPane.showMessageDialog(null, "Login failure!", "Error", JOptionPane.ERROR_MESSAGE);
			}
		}

	}

}